package introduction

import scala.io.Source._
object HelloWorld {
  def main(args: Array[String]): Unit = {
    variable()
    val a = 3
    val b = 4
    println(add(3,4))

    fileRead("D:\\test.txt")

    println(three())
    println(three)        // 当函数没有入参括号可以不写

    sayName()
    sayName("啊切")

    println(speed(100,10))
    println(speed(time = 10,distance = 100))  // 命名参数

    println(sumAll(1,2,3))

    println(1 to 10)        // 1.to(10)  Range 1 to 10
    println(Range(1, 10, 2))
    println(1 until 10)
    forTest()

    var courses = Array("Spark SQL","Spark Streaming", "Hadoop","Storm","Scala")
    for(course <- courses){
      print(course)
    }

    courses.foreach(course => println(course))

    // 一百个数字求和
    var (num, sum) = (100, 0)
    while(num > 0){   // 出口
      sum += num
      num -= 1        // 步长
    }
    printf("res: %d",sum)
  }

  // 不需要返回值
  def variable():Unit={
    val a: Double = 1.1                   // 常量
    var b:Float = 2.3f                    // 变量
    val c = a.asInstanceOf[Int]           // 类型转换
    println(c)

    val d = 10.isInstanceOf[Int] // 判断10 是否是某个类型
    println(d)

    lazy val e = 1                      // 只能修饰 val
    println(e.isInstanceOf[Int])         // 只有第一次使用才会发生操作
  }

  def add(x:Int, y:Int) :Int = {
    x + y           // 最后一行就是返回值
  }

  def fileRead(filename:String): Unit = {
    lazy val file:String = fromFile(filename).mkString
    println(file)
  }

  def three(): Int = 1 + 2      // 只有一行省略大括号

  // 默认参数
  def sayName(name:String = "aqie"): Unit = {
    if(name == "aqie"){
      println("please input name!")
    }else{
      println(name)
    }

  }

  def speed(distance:Float, time:Float):Float={
    distance / time
  }

  // 循环表达式
  def sumAll(numbers:Int*): Int ={
    var res = 0
    for (number <- numbers){
      res += number
    }
    res
  }

  def forTest(): Unit ={
    for(i <- 1 to 10 if i % 2 == 0){
      print(i)
    }
  }
}

